package com.xueyi.aixihu.interceptors;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.xueyi.aixihu.entity.po.DtUsers;
import com.xueyi.aixihu.entity.vo.DtUsersVo;
import com.xueyi.aixihu.exception.SzException;
import com.xueyi.aixihu.response.base.BaseResponse;
import com.xueyi.aixihu.status.SystemCode;
import com.xueyi.aixihu.utils.FinalUtil;
import com.xueyi.aixihu.utils.JedisUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 描述 请求的拦截器
 *
 * @auther 俞烨
 * @date 2022-08-13 14
 */
public class RequestInterceptor implements HandlerInterceptor {

    public static ThreadLocal<DtUsersVo> dtUsersLocal = new ThreadLocal<>();


    public static final List<String> phoneExcludeRuleList = Arrays.asList("/axh/findFinanceInformation", "/axh/findPublicFinanceList", "/axh/findDataBlackList", "/axh/findPublicSort");

    /**
     * 需要跳过权限验证的路径
     */
    public static final List<String> excludeRuleList = Arrays.asList(
//            "/axh/findMenu",
            "/axh/testRocketMq",
            "/axh/dtUsers/loginDtUsers",
            "/axh/findOneFinanceLogList",
            "/axh/api/searchVillageCommunity",
            "/axh/api/searchSystemType",
            "/axh/api/searchSystemTypeContent",
            "/axh/api/searchStatementContentDesc",
            "/axh/complaint/add"
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 从Request取出Token的信息，并进行校验
        String requestURI = request.getRequestURI();
        if (requestURI.charAt(1) == '/') {
            requestURI = requestURI.substring(1);
        }
        try {
            if (excludeRuleList.contains(requestURI)) {
                return true;
            }
            boolean phoneAuth = org.springframework.util.StringUtils.hasLength(request.getParameter("phoneAuth"));
            DtUsersVo userIsLogin = findUserIsLogin(request, phoneAuth);
            if (phoneAuth) {
                return true;
            }
            return userIsLogin.validateRule(request);
        } catch (SzException e) {
            response.setHeader("content-type", "text/html; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(BaseResponse.build(e.code, e.getMessage(), "")));
            response.getWriter().flush();
            return false;
        }
    }


    /**
     * 查询用户的登陆信息
     *
     * @param request
     * @return
     * @throws SzException
     */
    public DtUsersVo findUserIsLogin(HttpServletRequest request, boolean phoneAuth) throws SzException {

       /* DtUsersVo dtUsersVo = new DtUsersVo();
        List<String> roleIds = new ArrayList<>();
        roleIds.add("7");
        dtUsersVo.setRoleList(roleIds);
        dtUsersVo.setId(1);
        dtUsersLocal.set(dtUsersVo);
        return dtUsersVo;*/
        Jedis jedis = JedisUtil.getJedis();
        try {
            String axhToken = request.getHeader("axh-access-token");
            DtUsersVo dtUsersVo = null;
            String dtUsersJson = null;
            if (StringUtils.isEmpty(axhToken) || StringUtils.isEmpty((dtUsersJson = jedis.get(axhToken))) ||
                    (dtUsersVo = JSON.parseObject(dtUsersJson, DtUsersVo.class)) == null) {

                // 判断是否需要绕开
                if (phoneAuth) {
                    return null;
                } else {
                    throw new SzException(SystemCode.USER_NOT_LOGIN, "用户登陆过期");
                }

            }

            // 刷新token的过期时间
            jedis.expire(axhToken, 3600 * 12);

            if (dtUsersVo.getUserType() == 0 && new Date().compareTo(dtUsersVo.getExpireTime()) > -1) {

                DtUsersVo.deleteTokenDetail(dtUsersVo.getId());
                throw new SzException(SystemCode.USER_NOT_LOGIN, "游客期间到期");
            }

            // 说明用户登陆了
            dtUsersLocal.set(dtUsersVo);
            return dtUsersVo;
        } finally {
            FinalUtil.unLockAndCloseRedis(jedis);
        }
    }
}
